package org.jflame.context.security.mask.fastjson2;

import org.jflame.commons.reflect.BeanHelper;
import org.jflame.context.security.mask.Mask;
import org.jflame.context.security.mask.MaskHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson2.filter.ValueFilter;

/**
 * fastjson2脱敏注解序列化处理器
 * <p>
 * 使用方法: <br>
 * 1.在类上设置<code>@JSONType(serialzeFilters =MaskedValueFilter.class)</code><br>
 * 2.在需字段上加@Mask注解,设置脱敏规则
 * 
 * @author charles.zhang
 * @see Mask
 */
public class MaskedValueFilter implements ValueFilter {

    private static final Map<String,MaskHandler> MASK_HANDLER_CACHE = new ConcurrentHashMap<>();

    @Override
    public Object apply(Object object, String name, Object value) {
        if (value != null && value instanceof String strValue) {
            if (strValue.isBlank()) {
                return strValue;
            }
            Mask annot = BeanHelper.getPropertyAnnotation(object.getClass(), name, Mask.class);
            if (annot != null) {
                MaskHandler converter = MASK_HANDLER_CACHE.computeIfAbsent(key(object, name),
                        m -> MaskHandler.build(annot));
                return converter.apply(strValue);
            }
        }

        return value;
    }

    String key(Object object, String name) {
        return object.getClass()
                .getName() + "." + name;
    }
}
